<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="security" uri="http://www.springframework.org/security/tags"%>
<%@ taglib prefix="sf" uri="http://www.springframework.org/tags/form" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Edit your information</title>
    <script type="text/javascript" src="../../resources/js/jquery-1.6.js"></script>
    <script type="text/javascript" src="../../resources/js/jquery.form.js"></script>
    <script type="text/javascript" src="../../resources/js/jquery-validation-1.8.0/jquery.validate.js"></script>
    <script type="text/javascript" src="../../resources/js/jquery-validation-1.8.0/additional-methods.js"></script>
    <script type="text/javascript" src="../../resources/js/jquery-ui-1.8.11.custom.min.js"></script>
    <link rel="stylesheet" type="text/css" media="screen" href="../../resources/css/start/jquery-ui-1.8.10.custom.css"/>
    <style type="text/css">
        * {
            font-family: Verdana;
            font-size: 96%;
        }

        label {
            width: 10em;
            float: left;
        }

        label.error {
            float: none;
            color: red;
            padding-left: .5em;
            vertical-align: top;
        }

		.ui-dialog .ui-state-error { padding: .3em; }
		.validateTips { border: 1px solid transparent; padding: 0.3em; }

        p {
            clear: both;
        }

        .submit {
            margin-left: 12em;
        }

        em {
            font-weight: bold;
            padding-right: 1em;
            vertical-align: top;
        }

        body {
            font-size: 0.7em;
            font-weight: bold;
        }
    </style>
    <script>
        $(document).ready(function() {
            $("#cdateOfBirth").datepicker({
                changeMonth : true,
                changeYear : true
            });
           
            $("#ccity").autocomplete({
                source: function(request, response) {
                    jQuery.ajax({
                        url : "/search/cities",
                        dataType : "json",
                        data : {
                            term : request.term
                            //groupId : $("#groupId").val();
                        },
                        success : function(data) {
                            response(jQuery.map(data, function(item) {
                                return {
                                    label: item.ruName,
                                    value: item.ruName,
                                    id: item.idCity
                                }
                            }))
                        }
                    })
                },
                select: function(event, ui) {
                    if (ui.item) {
                        putCityId(ui.item.id);
                    }                
                },
                minLength : 2,
                open : function() {
                    $(this).removeClass("ui-corner-all").addClass("ui-corner-top");
                },
                close: function() {
                    $(this).removeClass("ui-corner-top").addClass("ui-corner-all");
                }
            });
           
            $("#editEmployerForm").validate({
                submitHandler: function(form) {
                if (fileExist() && findSize() && checkFileExtension()){
                    $(form).ajaxSubmit({
                                        success: function(data) {
                                            if ($.parseJSON(data).isOk) {
                                                if (self!=top) {
                                                    window.parent.closeIframe(true);
                                                } else {
                                                    window.location="/workers/${worker.idUser}";
                                                }
                                            } else {
                                                alert("Данные не были изменены(((");
                                            }
                                        }
                                    })
                               }
                        },
            	rules: {
                            firstName: {
                                required: true,
                                minlength: 2,
                                maxlength: 24
                            },
                            lastName: {
                                required: true,
                                minlength: 2,
                                maxlength: 24
                            },
                            city: {
                                min: 1,
                                required: true,
                                //remote: "validation/checkCity"
                            },
                            jobTypes: {
                                required: true
                            },
                            about: {
                                required: true
                            },
                            organization: {
                                required: true
                            }
                },
                messages: {

                            firstName: {
                                required: "Это поле обязательно для заполнения",
                                minlength: "Минимальная длинна имени - 2 символа",
                                maxlength: "Максимальная длинна имени - 24 символа"
                            },
                            lastName: {
                                required: "Это поле обязательно для заполнения",
                                minlength: "Минимальная длинна фамилии - 2 символа",
                                maxlength: "Максимальная длинна фамилии - 24 символа",
                            },
                            city: {
                                min: "К сожалению, такого города нет в нашей базе данных",
                                required: "Это поле обязательно для заполнения",
                                remote: "К сожалению, такого города нет в нашей базе данных"
                            },
                            jobTypes: {
                                required: "Это поле обязательно для заполнения"
                            },
                            about: {
                                required: "Это поле обязательно для заполнения"
                            },
                            organization: {
                                required: "Это поле обязательно для заполнения"
                            }
                }
            });
            
            $( "#dialog:ui-dialog" ).dialog( "destroy" );
    		
    		var oldpass = $( "#oldpass" ),
    			newpass = $( "#newpass" ),
    			confirmpass = $( "#confirmpass" ),
    			allFields = $( [] ).add( oldpass ).add( newpass ).add( confirmpass ),
    			tips = $( ".validateTips" );

    		function updateTips( t ) {
    			tips
    				.text( t )
    				.addClass( "ui-state-highlight" );
    			setTimeout(function() {
    				tips.removeClass( "ui-state-highlight", 1500 );
    			}, 500 );
    		}

    		$("#checkbox").buttonset();

    		function checkLength( o, n, min, max ) {
    			if ( o.val().length > max || o.val().length < min ) {
    				o.addClass( "ui-state-error" );
    				updateTips( "Length of " + n + " must be between " +
    					min + " and " + max + "." );
    				return false;
    			} else {
    				return true;
    			}
    		}

    		function checkRegexp( o, regexp, n ) {
    			if ( !( regexp.test( o.val() ) ) ) {
    				o.addClass( "ui-state-error" );
    				updateTips( n );
    				return false;
    			} else {
    				return true;
    			}
    		}
    		
    		$( "#dialog-form" ).dialog({
    			autoOpen: false,
    			height: 300,
    			width: 350,
    			modal: true,
    			buttons: {
    				"Change": function() {
    					var bValid = true;
    					allFields.removeClass( "ui-state-error" );

    					bValid = bValid && checkLength( oldpass, "old password", 6, 12 );
    					bValid = bValid && checkLength( newpass, "new password", 6, 12 );
    					bValid = bValid && checkLength( confirmpass, "confirm password", 6, 12 );

    					// From jquery.validate.js (by joern), contributed by Scott Gonzalez: http://projects.scottsplayground.com/email_address_validation/
    					bValid = bValid && checkRegexp( newpass, /^([0-9a-zA-Z])+$/, "Password field only allow : a-Z 0-9" );
    					bValid = bValid && checkRegexp( confirmpass, /^([0-9a-zA-Z])+$/, "Password field only allow : a-Z 0-9" );
							
    					bValid = bValid && newpass.val()==confirmpass.val();
    					if (newpass.val()!=confirmpass.val()) {
    						newpass.addClass( "ui-state-error" );
    	    				updateTips( "New password does not match the confirmation" );
    					}
    					
    					if ( bValid ) {
    						$.getJSON('/validation/changePassword',
    								{oldpass:oldpass.val(),
									 newpass:newpass.val(),
									 confirmpass:confirmpass.val()
									 },
    							function(data) {
									if (data.isOk) {
										$( "#dialog-form" ).dialog( "close" );			
									} else {
										oldpass.addClass( "ui-state-error" );
			    	    				updateTips( data.message );		
									}		 
									 })
    						
    					}
    				},
    				Cancel: function() {
    					$( this ).dialog( "close" );
    				}
    			},
    			close: function() {
    				allFields.val( "" ).removeClass( "ui-state-error" );
    			}
    		});

    		$( "#change-password" )
    			.button()
    			.click(function() {
    				$( "#dialog-form" ).dialog( "open" );
    			});
            
            
            
            
            
        });
        
        function putCityId(idCity) {
            $("#idCity").val(idCity);
        }


            function findSize() {
    if ( $.browser.msie ) {
       var a = document.getElementById('cimage').value;
           $('#myImage').attr('src',a);
           var imgbytes = document.getElementById('myImage').fileSize;
           //var imgkbytes = Math.round(parseInt(imgbytes)/1024);
           if (imgbytes>100000) {
           alert("Размер фотографии превышает 100кб. Добавьте пожалуйста фотографию с меньшим размером!");
                   return false; }
                   else {return true;}
    }else {
           var fileInput = $("#cimage")[0];
           var imgbytes = fileInput.files[0].fileSize; // Size returned in bytes.
           //var imgkbytes = Math.round(parseInt(imgbytes)/1024);
           if (imgbytes>100000) {
           alert("Размер фотографии превышает 100кб. Добавьте пожалуйста фотографию с меньшим размером!");
                   return false; }
                   else {return true;}
     }
}

function checkFileExtension(){
     var filename;

      if ( $.browser.msie ) {
      filename =  document.getElementById('cimage').value;

    }else {
           var fileInput = $("#cimage")[0];
           filename =  fileInput.value;

     }

    var ext = filename.split('.').pop();
    if((ext!="jpg") && (ext!="jpeg")) {
        alert("Допустимы фотографии только в формате jpg!");
        return false;
    }
    return true;
}

function fileExist(){
       if ( $.browser.msie ) {
       var a = document.getElementById('cimage').value;
           $('#myImage').attr('src',a);
           return document.getElementById('myImage').fileSize;


    }else {
           var fileInput = $("#cimage")[0];
           return fileInput.files[0].fileSize; // Size returned in bytes.

     }

}
    </script>

</head>
<body>

<div id="dialog-form" title="Change password">
<p class="validateTips">All form fields are required.</p>

	<form>
	<fieldset>
		<label for="oldpass">Old password</label>
		<input type="password" name="old" id="oldpass" class="text ui-widget-content ui-corner-all" />
		<label for="newpass">New password</label>
		<input type="password" name="newpass" id="newpass" value="" class="text ui-widget-content ui-corner-all" />
		<label for="confirmpass">Confirm password</label>
		<input type="password" name="confirmpass" id="confirmpass" value="" class="text ui-widget-content ui-corner-all" />
	</fieldset>
	</form>
</div>

<sf:form class="cmxform" modelAttribute="employer" id="editEmployerForm" method="post" action="/saveEditedEmployer" enctype="multipart/form-data">
    <fieldset>
        <!--<legend>Input information about yourself</legend>-->

        <sf:input path="idUser" hidden="hidden"/>
        <p>
            <label for="cemail">E-Mail</label>
            <em></em><input id="cemail" name="email" size="25" value="${employer.email}" readonly="true" disabled="disabled" class="email"/>
            <sf:input path="email" hidden="hidden"/>
        </p>

        <input type="button" id="change-password" value = "Изменить пароль"/>

        <p>
            <label for="cfirstName">Имя *</label>
            <em></em><sf:input path="firstName" id="cfirstName" name="firstName" size="25" class="required"/>
        </p>

        <p>
            <label for="clastName">Фамилия *</label>
            <em></em><sf:input path="lastName" id="clastName" name="lastName" size="25" class="required"/>
        </p>
        
        <p>
            <label for="corganization">Организация *</label>
            <em></em><sf:input path="organization" id="corganization" name="organization" size="25"/>
        </p>
        
        <p>
    		<label for="ccity">Город *</label>
    <em></em><input id="ccity" title="Начните печатать название города и выберите Ваш город из выпавшего списка."
    name="visicity" value="${employer.city.ruName }" size="25" class="required"/>
    <sf:input path="city" value="${employer.city.idCity }" id="idCity" type="hidden" name="city"/>
		</p>

        <p>
        <img id="myImage" src="" style="display:none;"><br>
        <label for="cimage">Фотография</label>
    <img alt="avatar" src="/employers/${employer.idUser}/getImage"/>
    <input type="file" id="cimage" name="file" size="25"/>
       </p>

<p>
    <label for="cphone">Телефон  </label>
    <em></em><sf:input path="phone" id="cphone" name="phone" size="25"/>
</p>

<p>
    <label for="cskype">Skype  </label>
    <em></em><sf:input path="skype" id="cskype" name="skype" size="25"/>
</p>

<p>
    <label for="cicq">Icq  </label>
    <em></em><sf:input id="cicq" path="icq" name="icq" size="25"/>
</p>

		<p>
    <label for="cabout">О себе *</label>
    <em>*</em><sf:textarea path="about" id="cabout" name="about"/>
</p>
<p>
        <label for="cjobTypesEnd">Предпочитаемые типы работы *</label>
    <em></em>
    <c:forEach var="employersJobType" items="${employersJobTypes}">
        ${employersJobType.title}:<sf:input path="jobTypes" id="cjobTypes" type="checkbox" name="jobTypes" checked="true" value="${employersJobType.idJob}" class="required" />
    </c:forEach>
    <c:forEach var="jobType" items="${jobTypes}">
        ${jobType.title}:<sf:input path="jobTypes" id="cjobTypes" type="checkbox" name="jobTypes" value="${jobType.idJob}" class="required" />
    </c:forEach>
    <input id="cjobTypesEnd" type="hidden"/>
</p>

        <input class="submit" type="submit" value="Изменить"/>

    </fieldset>
</sf:form>
</body>
</html>